package com.zhangxun.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangxun.domain.SysUser;
import com.zhangxun.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;


@Api
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @GetMapping("/info")
    @PreAuthorize("hasAuthority('sys:user:info')")
    @ApiOperation("查询当前登录用户信息")
    public ResponseEntity<SysUser> userInfo(){
        String s = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getById(Long.valueOf(s));

        return ResponseEntity.ok(sysUser);
    }

    @GetMapping("page")
    @ApiOperation("查询所有管理员")
    @PreAuthorize("hasAuthority('sys:user:page')")
    public Page<SysUser> page(Page<SysUser> page,SysUser sysUser) {
           page = sysUserService.userPage(page,sysUser);
        return page;
    }


    @PostMapping
    @ApiOperation("新增管理员,修改管理员，通过id确定是新增还是修改")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public ResponseEntity<Boolean> save(@RequestBody SysUser sysUser) {
        Boolean result = null;
        if(sysUser.getUserId() == null) {
            result = sysUserService.saveUserAndRoleId(sysUser);
        }else{
            result = sysUserService.updateUserAndRoleId(sysUser);
        }

       return ResponseEntity.ok(result);
    }


    @PutMapping("/password")
    @ApiOperation("修改密码")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public ResponseEntity<Boolean> password(@RequestBody SysUser sysUser){

        boolean result = sysUserService.updatePasswordById(sysUser);

        return ResponseEntity.ok(result);
    }

    @GetMapping("/info/{userId}")
    @ApiOperation("修改管理员信息，查询回显方法")
    @PreAuthorize("hasAuthority('sys:user:info')")
    public ResponseEntity<SysUser> updateUser(@PathVariable Long userId){
        return ResponseEntity.ok(sysUserService.getById(userId));
    }

//    @PostMapping
//    @ApiOperation("修改管理员信息，保存修改的管理员信息")
//    @PreAuthorize("hasAuthority('sys:user:update')")
//    public ResponseEntity<Boolean> saveUpdate(@RequestBody SysUser sysUser){
//        boolean result = sysUserService.updateUserAndRoleId(sysUser);
//
//        return ResponseEntity.ok(result);
//    }

}
